import { ref } from 'vue'
import axios from 'axios'
import { useFileStore } from '@/store/fileStore'

const __baseUrl = 'http://127.0.0.1:9426'

export function useFileProcessor() {
  const processing = ref(false)
  const processed = ref(false)
  const previewData = ref(null)
  const fileStore = useFileStore()

  const handleProcess = async () => {
    processing.value = true
    try {
      let formData = new FormData()
      const selectedFunction = fileStore.selectedFunction

      if (selectedFunction === 'upload_meter') {
        if (!fileStore.meterFiles.tpl) throw new Error('请上传模板文件')
        formData.append('templateFile', fileStore.meterFiles.tpl.raw)
        if (fileStore.meterFiles.remote) formData.append('remoteFile', fileStore.meterFiles.remote.raw)
        if (fileStore.meterFiles.computers && fileStore.meterFiles.computers.length) {
          fileStore.meterFiles.computers.forEach((f) => formData.append('computerFiles', f.raw))
        }
        const res = await axios.post(__baseUrl + '/upload_meter', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      } else if (selectedFunction === 'compare') {
        if (!fileStore.compareFiles.old || !fileStore.compareFiles.new) {
          throw new Error('请分别上传要比较的两个文件（旧表 和 新表）')
        }
        formData.append('files', fileStore.compareFiles.old.raw)
        formData.append('files', fileStore.compareFiles.new.raw)
        const opts = { key_column: fileStore.compareKey || 'ID' }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/compare', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      } else if (selectedFunction === 'sync_remarks') {
        if (!fileStore.compareFiles.old || !fileStore.compareFiles.new) {
          throw new Error('请分别上传主文件和副文件用于同步备注')
        }
        formData.append('files', fileStore.compareFiles.old.raw)
        formData.append('files', fileStore.compareFiles.new.raw)
        const opts = {
          key_columns: fileStore.syncKeyColumns || 'ID',
          remark_column: fileStore.syncRemarkColumn || '备注'
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/sync_remarks', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      } else if (selectedFunction === 'split_by_header') {
        if (!fileStore.fileList.length) throw new Error('请上传要拆分的文件（单个）')
        formData.append('files', fileStore.fileList[0].raw)
        const opts = {
          header_name: fileStore.splitHeaderName,
          extra_header: fileStore.splitExtraHeader || undefined,
          extra_values: fileStore.splitExtraValues || undefined,
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/split_by_header', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      } else if (selectedFunction === 'sample_meter_list') {
        if (!fileStore.fileList.length) throw new Error('请上传用户清单文件（单个）')
        formData.append('files', fileStore.fileList[0].raw)
        const opts = {
          header_name: fileStore.sampleHeaderName,
          filter_values: fileStore.sampleFilterValues,
          total_count: Number(fileStore.sampleTotalCount) || 400
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/sample_meter_list', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      } else if (selectedFunction === 'filter_common_values') {
        if (!fileStore.compareFiles.old || !fileStore.compareFiles.new) {
          throw new Error('请分别上传要对比的两个文件（第一个为要筛选的表，第二个为参考表）')
        }
        formData.append('files', fileStore.compareFiles.old.raw)
        formData.append('files', fileStore.compareFiles.new.raw)
        const opts = {
          header_name: fileStore.filterHeaderName || '用户编号'
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/filter_common_values', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      } else if (selectedFunction === 'compare_header_consistency') {
        if (!fileStore.compareFiles.old || !fileStore.compareFiles.new) {
          throw new Error('请分别上传要对比的两个文件')
        }
        formData.append('files', fileStore.compareFiles.old.raw)
        formData.append('files', fileStore.compareFiles.new.raw)
        const opts = {
          match_header: fileStore.consistencyMatchHeader || 'ID',
          compare_header: fileStore.consistencyCompareHeader || '金额'
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/compare_header_consistency', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      }
      // 新增功能处理
      else if (selectedFunction === 'format_survey_enhanced') {
        if (!fileStore.fileList.length) throw new Error('请上传要处理的文件')
        fileStore.fileList.forEach((f) => formData.append('files', f.raw))
        const opts = {
          title_text: fileStore.surveyEnhancedTitleText || '水表普查清单',
          start_index: Number(fileStore.surveyEnhancedStartIndex) || 0,
          end_index: fileStore.surveyEnhancedEndIndex ? Number(fileStore.surveyEnhancedEndIndex) : undefined,
          columns_to_keep: fileStore.surveyEnhancedColumnsToKeep ? fileStore.surveyEnhancedColumnsToKeep.split(',') : undefined
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/format_survey_enhanced', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      }
      else if (selectedFunction === 'split_by_header_enhanced') {
        if (!fileStore.fileList.length) throw new Error('请上传要拆分的文件（单个）')
        formData.append('files', fileStore.fileList[0].raw)
        const opts = {
          header_name: fileStore.splitEnhancedHeaderName,
          split_to: fileStore.splitEnhancedSplitTo || 'files',
          extra_header: fileStore.splitEnhancedExtraHeader || undefined,
          extra_values: fileStore.splitEnhancedExtraValues || undefined,
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/split_by_header_enhanced', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      }
      else if (selectedFunction === 'sample_data') {
        if (!fileStore.fileList.length) throw new Error('请上传数据文件')
        formData.append('files', fileStore.fileList[0].raw)
        const opts = {
          header_name: fileStore.sampleDataHeaderName || undefined,
          filter_values: fileStore.sampleDataFilterValues || undefined,
          total_count: Number(fileStore.sampleDataTotalCount) || 400,
          output_file: fileStore.sampleDataOutputFile || '抽样结果.xlsx',
          columns_to_keep: fileStore.sampleDataColumnsToKeep ? fileStore.sampleDataColumnsToKeep.split(',') : undefined
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/sample_data', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      }
      else if (selectedFunction === 'budget_calculation') {
        if (!fileStore.fileList.length) throw new Error('请上传预算模板文件')
        formData.append('files', fileStore.fileList[0].raw)
        const opts = {
          target_amount: Number(fileStore.budgetTargetAmount) || 3700,
          users: fileStore.budgetUsers ? JSON.parse(fileStore.budgetUsers) : []
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/budget_calculation', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      }
      else if (selectedFunction === 'merge_excel_files') {
        if (!fileStore.fileList.length) throw new Error('请上传要合并的Excel文件')
        fileStore.fileList.forEach((f) => formData.append('files', f.raw))
        const opts = {
          output_filename: fileStore.mergeOutputFilename || '合并文件.xlsx'
        }
        formData.append('options', JSON.stringify(opts))
        const res = await axios.post(__baseUrl + '/merge_excel_files', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      }
      else {
        // 原有通用处理逻辑
        if (!fileStore.fileList.length) throw new Error('请先选择文件再处理！')
        fileStore.fileList.forEach((f) => formData.append('files', f.raw))
        formData.append('method', selectedFunction)

        if (selectedFunction === 'format_survey_files') {
          formData.append(
            'options',
            JSON.stringify({
              name: fileStore.surveyName,
              start_index: Number(fileStore.surveyStart),
              end_index: Number(fileStore.surveyEnd)
            })
          )
        }

        const res = await axios.post(__baseUrl + '/upload', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 'error') throw new Error(res.data.message)
      }

      const previewRes = await axios.get(__baseUrl + '/preview')
      if (previewRes.data.status === 'error') throw new Error(previewRes.data.message)

      previewData.value = previewRes.data.data
      processed.value = true
      ElMessage.success('处理完成')
    } catch (err) {
      console.warn(err)
      ElMessage.error(err.response?.data?.message || err.message || '处理失败')
      processed.value = false
      previewData.value = null
    } finally {
      processing.value = false
    }
  }

  const handleDownload = () => {
    if (!processed.value) {
      ElMessage.warning('请先处理文件再下载！')
      return
    }
    window.open(__baseUrl + '/download', '_blank')
  }

  return {
    processing,
    processed,
    previewData,
    handleProcess,
    handleDownload
  }
}